package com.yunshan.welfare;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshan.common.utils.StringUtils;
import com.yunshan.member.domain.MemberUserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.yunshan.common.annotation.Log;
import com.yunshan.common.core.controller.BaseController;
import com.yunshan.common.core.domain.AjaxResult;
import com.yunshan.common.enums.BusinessType;
import com.yunshan.welfare.domain.WelfareCouponRecord;
import com.yunshan.welfare.service.IWelfareCouponRecordService;
import com.yunshan.common.utils.poi.ExcelUtil;
import com.yunshan.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import static com.yunshan.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 优惠券发放详情Controller
 *
 * @author yunshan
 * @date 2025-01-20
 */
@Api(tags = "优惠券发放详情管理")
@RestController
@RequestMapping("/welfare/couponRecord")
public class WelfareCouponRecordController extends BaseController
{
    @Autowired
    private IWelfareCouponRecordService welfareCouponRecordService;
    // 手机号正则表达式
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    /**
     * 查询优惠券发放详情列表
     */
    @ApiOperation("查询优惠券发放详情列表")
    @GetMapping("/list")
    public TableDataInfo list(WelfareCouponRecord welfareCouponRecord)
    {
        startPage();
        List<WelfareCouponRecord> list = welfareCouponRecordService.selectWelfareCouponRecordList(welfareCouponRecord);
        return getDataTable(list);
    }

    /**
     * 查询优惠券发放详情列表（不分页）
     */
    @ApiOperation("查询优惠券发放详情列表（不分页）")
    @GetMapping("/query")
    public AjaxResult query(WelfareCouponRecord welfareCouponRecord)
    {
        List<WelfareCouponRecord> list = welfareCouponRecordService.selectWelfareCouponRecordQuery(welfareCouponRecord);
        return success(list);
    }

    /**
     * 导出优惠券发放详情列表
     */
    @ApiOperation("导出优惠券发放详情列表")
    @Log(title = "优惠券发放详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WelfareCouponRecord welfareCouponRecord)
    {
        List<WelfareCouponRecord> list = welfareCouponRecordService.selectWelfareCouponRecordList(welfareCouponRecord);
        ExcelUtil<WelfareCouponRecord> util = new ExcelUtil<WelfareCouponRecord>(WelfareCouponRecord.class);
        util.exportExcel(response, list, "优惠券发放详情数据");
    }

    /**
     * 获取优惠券发放详情详细信息
     */
    @ApiOperation("获取优惠券发放详情详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(welfareCouponRecordService.selectWelfareCouponRecordById(id));
    }

    /**
     * 新增优惠券发放详情
     */
    @ApiOperation("新增优惠券发放详情")
    @Log(title = "优惠券发放详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> map)
    {
        try {
            WelfareCouponRecord welfareCouponRecord = new ObjectMapper()
                    .convertValue(map.get("welfareCouponRecord"), WelfareCouponRecord.class);

            Object rawIds = map.get("ids");
            if (!(rawIds instanceof List<?>)) {
                return error("ids参数格式错误");
            }

            List<Long> ids = ((List<?>) rawIds).stream()
                    .map(obj -> {
                        if (obj instanceof Number) {
                            return ((Number) obj).longValue();
                        }
                        throw new IllegalArgumentException("ids列表包含非数值类型数据");
                    })
                    .collect(Collectors.toList());

            return success(welfareCouponRecordService.insertWelfareCouponRecord(welfareCouponRecord, ids));
        }catch (Exception e){
            log.error("发放失败：{}",e.getMessage());
            return error(e.getMessage());
        }
    }

    /**
     * 修改优惠券发放详情
     */
    @ApiOperation("修改优惠券发放详情")
    @Log(title = "优惠券发放详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WelfareCouponRecord welfareCouponRecord)
    {
        return toAjax(welfareCouponRecordService.updateWelfareCouponRecord(welfareCouponRecord));
    }

    /**
     * 删除优惠券发放详情
     */
    @ApiOperation("删除优惠券发放详情")
    @Log(title = "优惠券发放详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(welfareCouponRecordService.deleteWelfareCouponRecordByIds(ids));
    }

    @ApiOperation("批量发放礼包")
    @Log(title = "礼包发放", businessType = BusinessType.INSERT)
    @PostMapping("/batch-import")
    public AjaxResult batchImport(
            @RequestParam Long couponId,
            @RequestParam("file") MultipartFile file,
            @RequestParam("endTimes")  String endTimes,
            @RequestParam("num")  Integer num){
        try {

            // 1. 校验文件有效性
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            if (!file.getOriginalFilename().endsWith(".xlsx")) {
                return error("仅支持xlsx格式文件");
            }

            // 2. 解析Excel数据
            List<MemberUserInfo> userList = new ArrayList<>();
            try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
                Sheet sheet = workbook.getSheetAt(0);

                for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第2行开始
                    Row row = sheet.getRow(i);
                    if (row == null) {
                        continue;
                    }

                    MemberUserInfo user = new MemberUserInfo();
                    // 解析姓名（A列）
                    user.setName(getCellStringValue(row.getCell(0)));
                    // 解析手机号（B列）
                    user.setPhone(getCellStringValue(row.getCell(1)));

                    // 数据校验
                    if (StringUtils.isEmpty(user.getName())) {
                        return error("第" + (i + 1) + "行姓名不能为空");
                    }
                    if (!user.getPhone().matches(PHONE_REGEX)) {
                        return error("第" + (i + 1) + "行手机号格式错误");
                    }

                    userList.add(user);
                }
            }

            // 3. 调用服务层进行批量保存
            return success(welfareCouponRecordService.batchInsertCouponRecords(couponId, userList, endTimes, num));
        }catch (Exception e){
            log.error("");
            return error("发放失败，请稍后重试");
        }

    }

    // 辅助方法：获取单元格值
    private String getCellStringValue(Cell cell) {
        if (cell == null){ return "";}
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue().trim();
    }
}
